package com.ganbo.stock.service.impl;

import com.ganbo.stock.entity.Stock;
import com.ganbo.stock.enums.ServiceType;
import com.ganbo.stock.utils.FastJsonUtil;
import com.ganbo.stock.repository.StockRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 股票
 * Created by gan on 2020/12/26 20:17.
 */

@Service
@Slf4j
public class StockService extends BaseService {

    @Autowired
    StockRepository stockRepository;

    
    public void save(Stock stock) {
        stockRepository.save(stock);
    }

    
    public void init() {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("licence", ig507Config.getLicence());
            List<Stock> list = sendReqReturnList(ServiceType.STOCK_LIST, params, Stock.class);

            for (Stock stock : list) {
                Stock stockDb = stockRepository.findByDm(stock.getDm());
                if (Objects.isNull(stockDb)) {
                    stock.setUpdateCompanyVersion(0);
                    stockRepository.save(stock);
                    log.info("新增股票标的,{}：", FastJsonUtil.objectTOJsonString(stock));
                }
            }
        } catch (Exception e) {
            log.error("拉取股票标的失败,", e);
        }
    }

    
    public List<Stock> findAll() {
        return stockRepository.findAll();
    }

    
    public Stock findByDm(String dm) {
        return stockRepository.findByDm(dm);
    }

    
    public Stock getUpdateCompanyStock() {
        Page<Stock> page = stockRepository.findMinVersion(PageRequest.of(0, 1));
        List<Stock> stockList = page.getContent();
        if (!CollectionUtils.isEmpty(stockList)) return stockList.get(0);
        return null;
    }
}
